#!/usr/bin/env python3
import smtplib, email.message, subprocess
from email.mime.text import MIMEText
from email.header import Header
import sys
sys.path.insert(0, r'/home/george/Projects/ISH') # Change to install path.. like /opt/something
import dialog

GMAIL_SMTP_SERVER = "smtp.gmail.com"
GMAIL_SMTP_PORT = 587

GMAIL_EMAIL = "gbredberg@gmail.com"
GMAIL_PASSWORD = "doureallythinkiwillputmypwdhere?"

def initialize_smtp_server():
    '''Initialize and greet smtp server.
    
    This function initializes and greets the smtp server.
    It logs in using the provided credentials and returns 
    the smtp server object as a result.
    '''
    smtpserver = smtplib.SMTP(GMAIL_SMTP_SERVER, GMAIL_SMTP_PORT)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo()
    smtpserver.login(GMAIL_EMAIL, GMAIL_PASSWORD)
    return smtpserver

def send_email(to_email, issue, log_file):
    # We start a progressbar so the user see's that we are doing something.
    pid = subprocess.Popen(["./progress.py"], stdin=subprocess.PIPE)
    headline = issue.encode ('utf-8')
    pid.communicate(input=headline)[0]

    from_email = GMAIL_EMAIL
    subject = issue + " från " + to_email
    # log_file is a global from support.py
    f = open(log_file, 'r')
    # Create a text/plain message
    msg = (f.read())
    f.close()
    
    content = MIMEText(msg.encode('utf-8'), 'plain', 'utf-8')
    content['From'] = from_email
    content['To'] = to_email
    content['Subject'] = Header(subject, 'utf-8') # Python 3 needs header for Subject.
    
    smtpserver = initialize_smtp_server()
    try:
        smtpserver.sendmail(from_email, [to_email], content.as_string())
        subprocess.Popen.kill(pid)
        dialog.info_message("Din fråga har skickats till support@bona.nu.\nEn kopia skickades till " + to_email)
        smtpserver.close()
    except smtplib.SMTPException:
        subprocess.Popen.kill(pid)
        dialog.error_message("Kunde inte skicka.. Har du angett fel email-adress?\nI vilket fall är något fel. Avslutar.")
        sys.exit(1)

if __name__ == "__main__":
    # for every line of input (email-addresses to send to).
#    for email in sys.stdin.readlines():
#            send_email(email)
    send_email(to_email, issue, log_file) # Will need to send to at least two addresses.
